package cn.kgc.commons.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>添加描述信息</p>
 *
 */
@Component
public class RedisUtil {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    //lua脚本
    private static final String lua="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1])" +
            "else return 0 end";

    //执行lua脚本,实现分布式锁中删除锁的操作
    public boolean execute(String lockName,String uuid){
        long result = redisTemplate.execute(
                new DefaultRedisScript<Long>(lua,Long.class),
                Arrays.asList(lockName),
                uuid
        ).longValue();
        return result==1;
    }

    public  void set(String key,Object value,long times,TimeUnit timeUnit){
        redisTemplate.opsForValue().set(key,value,times,timeUnit);
    }

    public void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }


    public Object get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }

    public boolean setIfAbsent(String key,Object value,long times,TimeUnit timeUnit){
        return redisTemplate.opsForValue().setIfAbsent(key,value,times,timeUnit);
    }

    public boolean haskey(String key){
        return redisTemplate.hasKey(key);
    }
    //key value(haskey,hvalue)
    public boolean hasKey(String key,Object hk){
        return redisTemplate.opsForHash().hasKey(key,hk);
    }
    //获得hash类型中的value值
    public Object get(String key,Object hk){
        return redisTemplate.opsForHash().get(key,hk);
    }
    //保存hash类型数据
    public boolean putKey(String key,Object hk,Object hv){
        redisTemplate.opsForHash().put(key,hk,hv);
        return true;
    }
    //根据key获得Hash类型的所有数据
    public Map<Object,Object> getHash(String key){
        return redisTemplate.opsForHash().entries(key);
    }
    public boolean delete(String key){
        return redisTemplate.delete(key);
    }
}